/**
 * Created by gek on 2016/3/4.
 */
var appDirectives = angular.module('appDirectives', []);

appDirectives.directive('sliders', function () {
  return function (scope, element, attrs) {
    var sliders = element.find('.sliders');

    var timer = setInterval(function () {
      goToNext();
    }, 3000);

    element.find('#icons-line').find('div').click(function () {
      var index = $(this).index();
      resetTimer();
      for (var i = 0; i < sliders.length; i++) {
        var slider = sliders.eq(i);
        goToIndex(slider, index);
      }
    });

    element.find('.left').click(function () {
      goToPrev();
      resetTimer();
    });

    element.find('right').click(function () {
      goToNext();
      resetTimer();
    });

    function resetTimer() {
      clearInterval(timer);
      timer = setInterval(function () {
        goToNext();
      }, 3000);
    }

    function goToIndex(slider, index) {
      var current = slider.find('.active');
      if (index == current.index()) return;
      var next = slider.find('div').eq(index);
      next.addClass('active');
      current.removeClass('active');
      current.addClass('to-leave');
      setTimeout(function () {
        current.removeClass('to-leave');
      }, 1000);
    }

    function goToNext() {
      for (var i = 0; i < sliders.length; i++) {
        var slider = sliders.eq(i);
        var currentIndex = slider.find('.active').index();
        var nextIndex = ++currentIndex;
        if (nextIndex >= slider.find('div').length) nextIndex = 0;
        goToIndex(slider, nextIndex);
      }
    }

    function goToPrev() {
      for (var i = 0; i < sliders.length; i++) {
        var slider = sliders.eq(i);
        var currentIndex = slider.find('.active').index();
        var nextIndex = --currentIndex;
        if (nextIndex < 0) nextIndex = slider.find('div').length - 1;
        goToIndex(slider, nextIndex);
      }
    }

    scope.goToNext = function () {
      resetTimer();
      goToNext();
    };

    scope.goToPrev = function () {
      resetTimer();
      goToPrev();
    };
  }
});

appDirectives.directive('swiper', function () {
  return function (scope, element, attrs) {
    var h = element.find('.swiper-wrapper').height();
    var swiper = new Swiper(element, {
      direction: 'vertical',
      height: h
    });
  }
});

appDirectives.directive('switch', function ($timeout) {
  return function (scope, element, attrs) {
    scope.isWeixin = false;
    var buttons = element.find('button');
    buttons.mouseenter(callback).mouseleave(callback);
    function callback() {
      var me = $(this);
      $timeout(function () {
        scope.isWeixin = me.index() == 1;
      });
    }
  }
});

